package com.imau.controller;

import com.imau.bean.User;
import com.imau.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class UserRegisterServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String code =(String)req.getSession().getAttribute("checkCode");

        //获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

        //校验验证码
        if( !"".equals(checkCode) && code.equalsIgnoreCase(checkCode))
        {

            //注册用户
            boolean b = userService.registerUser(new User(null, username, password));

            if(b)
            {
                resp.sendRedirect(req.getContextPath()+"/login.html");
            }else {

                resp.sendRedirect(req.getContextPath()+"/register.html");

            }

        }else { //验证码错误

            resp.sendRedirect(req.getContextPath()+"/register.html");

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
